/**
 * 项目状态管理
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getProjects } from '@/api/project'
import type { ProjectResponse } from '@/api/project'

export interface ProjectOption {
  value: string
  label: string
  description?: string
  category?: string
  created_by?: string
  created_at?: string
}

export const useProjectStore = defineStore('project', () => {
  // 状态
  const projects = ref<ProjectOption[]>([])
  const loading = ref(false)
  const lastFetchTime = ref<number>(0)
  const searchCache = ref<Map<string, ProjectOption[]>>(new Map())
  
  // 请求去重机制
  const isLoaded = ref(false)
  const loadingPromise = ref<Promise<ProjectOption[]> | null>(null)
  
  // 计算属性
  const isDataFresh = computed(() => {
    return Date.now() - lastFetchTime.value < 10 * 60 * 1000 // 10分钟内的数据视为新鲜
  })
  
  const projectOptions = computed(() => {
    return projects.value.map(project => ({
      label: project.label,
      value: project.value,
      disabled: project.category === 'archived'
    }))
  })
  
  const activeProjects = computed(() => {
    return projects.value.filter(project => 
      project.category !== 'archived' && project.category !== 'cancelled'
    )
  })
  
  // 方法
  async function fetchProjects(search?: string, forceRefresh = false) {
    // 检查缓存（仅对无搜索条件的请求使用缓存）
    const cacheKey = search || 'all'
    if (!search && !forceRefresh && isLoaded.value) {
      const existingPromise = loadingPromise.value
      if (existingPromise) {
        // 如果有正在进行的请求，等待它完成
        return await existingPromise
      }
      // 如果已加载且没有进行中的请求，直接返回缓存的数据
      if (projects.value.length > 0) {
        return projects.value
      }
    }
    
    // 检查搜索结果缓存
    if (search && searchCache.value.has(cacheKey)) {
      return searchCache.value.get(cacheKey)!
    }
    
    // 检查是否有正在进行的请求（仅对无搜索条件的请求）
    if (!search) {
      const existingPromise = loadingPromise.value
      if (existingPromise) {
        // 如果有正在进行的请求，等待它完成而不是发起新请求
        return await existingPromise
      }
    }
    
    loading.value = true
    
    const requestPromise = (async () => {
      try {
        const response = await getProjects({
          search,
          page: 1,
          size: 100,
          is_archived: false
        })
        
        // 处理统一API响应格式
        // getProjects API返回的是 response.data，即整个ApiResponse对象: { success: true, data: [...], ... }
        // 根据用户提供的实际响应，data字段直接是项目数组
        let projectData: ProjectResponse[] = []
        
        if (response && response.success && response.data) {
          if (Array.isArray(response.data)) {
            // 直接是项目数组（实际API返回格式）
            projectData = response.data
          } else if (typeof response.data === 'object' && 'data' in response.data) {
            // 嵌套格式：{ data: { data: [...], pagination: {...} } }（备用格式）
            projectData = Array.isArray((response.data as any).data) ? (response.data as any).data : []
          }
          
          console.log(`解析项目数据，数量: ${projectData.length}`)
          
          const projectList = projectData.map((item: ProjectResponse) => ({
            value: item.id,
            label: item.name,
            description: item.description,
            category: item.status,
            created_by: item.created_by,
            created_at: item.created_at
          }))
          
          console.log(`项目选项映射完成，数量: ${projectList.length}`)
          
          if (search) {
            // 缓存搜索结果
            searchCache.value.set(cacheKey, projectList)
          } else {
            projects.value = projectList
            lastFetchTime.value = Date.now()
            isLoaded.value = true
          }
          
          return projectList
        } else {
          ElMessage.error(response?.message || '获取项目数据失败')
          return []
        }
      } catch (error: any) {
        console.error('获取项目数据失败:', error)
        ElMessage.error(error.message || '获取项目数据失败')
        if (!search) {
          isLoaded.value = false
        }
        return []
      } finally {
        loading.value = false
        if (!search) {
          loadingPromise.value = null
        }
      }
    })()
    
    // 仅对无搜索条件的请求保存Promise
    if (!search) {
      loadingPromise.value = requestPromise
    }
    
    return requestPromise
  }
  
  async function searchProjects(query: string): Promise<ProjectOption[]> {
    if (!query.trim()) {
      return projects.value
    }
    
    return await fetchProjects(query)
  }
  
  function getProjectById(projectId: string): ProjectOption | undefined {
    return projects.value.find(project => project.value === projectId)
  }
  
  function getProjectsByStatus(status: string): ProjectOption[] {
    return projects.value.filter(project => project.category === status)
  }
  
  function clearCache() {
    searchCache.value.clear()
    isLoaded.value = false
    loadingPromise.value = null
  }
  
  /**
   * 刷新项目列表
   */
  async function refreshProjects(): Promise<ProjectOption[]> {
    lastFetchTime.value = 0
    clearCache()
    return await fetchProjects(undefined, true)
  }
  
  // 清理函数
  function $reset() {
    projects.value = []
    loading.value = false
    lastFetchTime.value = 0
    searchCache.value.clear()
    isLoaded.value = false
    loadingPromise.value = null
  }
  
  return {
    // 状态
    projects,
    loading,
    lastFetchTime,
    
    // 计算属性
    isDataFresh,
    projectOptions,
    activeProjects,
    
    // 方法
    fetchProjects,
    searchProjects,
    getProjectById,
    getProjectsByStatus,
    clearCache,
    refreshProjects,
    $reset
  }
})